## Controller Python Script "survey_edit"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind state=state
##bind subpath=traverse_subpath
##parameters=page=None
##title=Survey edit

REQUEST=context.REQUEST
from Products.CMFPlone import transaction_note

questions = context.listQuestions(pages=page)

MARKER=[]

for q in questions:
	id  = q.getId()
	question_fields = [field for field in q.getInternalFields() if field.mode != 'r' ]

	kws = {}
	for field in question_fields:
		name = field.getName()
		fid = '%s_%s' % (id, name)
		rval = REQUEST.get(fid, None)
		kws[name] = rval
		
	q.edit(**kws) 

msg='Changes saved'
transaction_note(msg)

next = not REQUEST.get('next', None) is None
previous = not REQUEST.get('prev', None) is None

if next or previous:
    s_names = [s for s in context.getPages() if s != 'metadata']

    if previous:
        s_names.reverse()

    next_schemata = None
    try:
        index = s_names.index(page)
    except ValueError:
        raise 'Non-existing fieldset: %s' % page
    else:
        index += 1
        if index < len(s_names):
            next_schemata = s_names[index]
            return state.set(page=next_schemata,
                             portal_status_message=msg)

    if next_schemata != None:
        return state.set(page=next_schemata, \
                 portal_status_message=msg)
    else:
        raise 'Unable to find next field set after %s' % page

return state.set(portal_status_message=msg)